package bootstrap

import (
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en_translation "github.com/go-playground/validator/v10/translations/en"
	zh_translation "github.com/go-playground/validator/v10/translations/zh"
	"shopstar/core/validate"
)

func InitValidate(locale string) {
	v, ok := binding.Validator.Engine().(*validator.Validate) // 将gin的验证器断言成 github.com/go-playground/validator/v10的验证器类型

	if !ok {
		return
	}

	// 注册一个对错误信息翻译的工具
	if ok = translator(locale, v); !ok {
		return
	}

	for _, val := range validate.Validators() { // 遍历所有要验证字段的自定义验证器
		//v.RegisterValidation(tag, val) // 验证器注册
		validate.RegisterValidatorFunc(v, val.Tag(), val.Error(), val.ValidateFn()) // 将自定义验证的结果按照自己想输出的内容返回给前端
	}
}

func translator(locale string, v *validator.Validate) (ok bool) {
	// 创建出中文和英文的翻译器
	zhT := zh.New()
	enT := en.New()
	// 构建一个语言环境
	uni := ut.New(enT, zhT, enT)
	validate.Trans, ok = uni.GetTranslator(locale)
	if !ok {
		return
	}
	switch locale {
	case "en":
		en_translation.RegisterDefaultTranslations(v, validate.Trans)
	case "zh":
		zh_translation.RegisterDefaultTranslations(v, validate.Trans)
	default:
	}
	return true
}
